﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TSharp.Core.Authentication.Facade;
using System.Net.Mail;
using System.ComponentModel;

namespace SendMailAndReceiveMail
{
    class JMailService : IMailService
    {
        public bool Send(string Host, int Port, int Timeout, bool EnableSsl,
            string UserName, string PassWord, MailMessage Message, bool IsSync,
            SendCompletedEventHandler CompletedCallBack)
        {
            jmail.Message MailObj = new jmail.MessageClass();
            MailObj.From = Message.From.Address;  //发件人的地址
            MailObj.Logging = true;
            MailObj.MailServerUserName = UserName;   //发件人用户名
            MailObj.MailServerPassWord = PassWord; //服务器验证
            MailObj.HTMLBody = Message.Body;
            MailObj.Charset = Message.BodyEncoding.EncodingName;// "gb2312";
            MailObj.Subject = Message.Subject;
            MailObj.FromName = Message.From.DisplayName;
         
            Message.To.Where(x =>
            {
                MailObj.AddRecipient(x.Address, x.DisplayName, null);  //添加接收人
                // MailObj.AddRecipient("", "User", "A");  //添加接收人
                return false;
            });

            MailObj.Priority = 3;
            Message.Attachments.Where(x =>
            {
                MailObj.AddAttachment(x.Name, false, x.ContentType.Name);
                return false;
            });
            // Message.Headers.

            try
            {

                bool bool_OK = MailObj.Send(Host, IsSync);
                if (CompletedCallBack != null)
                {
                    AsyncCompletedEventArgs e = new AsyncCompletedEventArgs(null, false, this);
                    CompletedCallBack(this, e);
                }
                return bool_OK;
            }
            catch (Exception ex)
            {
                if (CompletedCallBack != null)
                {
                    AsyncCompletedEventArgs e = new AsyncCompletedEventArgs(ex, false, this);
                    CompletedCallBack(this, e);
                }
                return false;
            }
        }
    }
}
